<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="政策名称" prop="policyName">
          <el-input
            v-model="queryParams.policyTitle"
            placeholder="请输入政策名称"
            clearable
            width="300"
            style="width:240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="对海政通状态" prop="isHztVisible">
          <el-select v-model="queryParams.isHztVisible">
            <el-option label="全部" :value="null"/>
            <el-option label="启用" :value="1"/>
            <el-option label="禁用" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="对公众状态" prop="isPublicVisible">
          <el-select v-model="queryParams.isPublicVisible">
            <el-option label="全部" :value="null"/>
            <el-option label="启用" :value="1"/>
            <el-option label="禁用" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="标签状态" prop="isHztVisible">
          <el-select v-model="queryParams.policyGroup">
            <el-option label="全部" :value="null"/>
            <el-option label="完整" :value="1"/>
            <el-option label="缺失" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>

          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['monitor:policy:export']"
          >导出
          </el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getTableData"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="policyList" @selection-change="handleSelectionChange">
        <!--        <el-table-column type="selection" width="55" align="center"/>-->
        <el-table-column label="政策编号" width="80" align="center" prop="policyId"/>
        <el-table-column label="政策名称" align="left" width="200" prop="policyTitle" :show-overflow-tooltip="true"/>
        <el-table-column label="归属核心政策" align="center" prop="policyGroup">
          <template slot-scope="scope">
            <dict-tag v-for="item in scope.row['coreIds']" :options="dict.type.core_policies" :value="item"/>
          </template>
        </el-table-column>
        <el-table-column label="入库时间" align="center" prop="createdTime" :show-overflow-tooltip="true"/>
        <el-table-column label="已有/全部标签" align="center" prop="cronExpression" :show-overflow-tooltip="true"/>
        <el-table-column label="对海政通状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isHztVisible"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row, 'isHztVisible')"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="对公众状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isPublicVisible"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row, 'isPublicVisible')"
            ></el-switch>
          </template>
        </el-table-column>
        <!--        <el-table-column label="状态" align="center">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-switch-->
        <!--              v-model="scope.row.status"-->
        <!--              active-value="0"-->
        <!--              inactive-value="1"-->
        <!--              @change="handleStatusChange(scope.row)"-->
        <!--            ></el-switch>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="专员/专家" align="center" prop="policyGroup">
          <template slot-scope="scope">
            <div>
              <p>专家：{{ getExpertName(scope.row) }}</p>
              <p>专员: {{ getOfficerName(scope.row) }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleShowTags(scope.row)"
              v-hasPermi="['monitor:policy:edit']"
            >查看标签内容
            </el-button>
            <el-button
              size="mini"
              type="text"

              @click="handleEditAssignment(scope.row)"
              v-hasPermi="['monitor:policy:remove']"
            >专员专家
            </el-button>
            <el-button
              size="mini"
              type="text"

              @click="handleEditCoreIds(scope.row)"
              v-hasPermi="['monitor:policy:remove']"
            >归属政策
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getTableData"
      />
    </el-row>


    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="政策名称">{{ form.policyTitle }}</el-form-item>
            <el-form-item label="归属核心政策">
              <el-select v-model="form.coreIds" multiple placeholder="选择归属核心政策" maxlength="30">
                <el-option v-for="item in dict.type.core_policies" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCoreId">确 定</el-button>
        <el-button @click="cancelCoreId">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="assignmentOpen" width="600px" append-to-body>
      <el-form ref="form" :model="assignmentForm" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="政策名称">{{ assignmentForm.policyTitle }}</el-form-item>
            <el-form-item label="政策专家">
              <el-select v-model="assignmentForm.expertId" placeholder="选择专家" maxlength="30">
                <el-option :key="`expert-${item.userId}`" v-for="item in experts" :label="item.nickName"
                           :value="item.userId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="政策专员">
              <el-select v-model="assignmentForm.officerId" placeholder="选择专员" maxlength="30">
                <el-option :key="`officer-${item.userId}`" v-for="item in officers" :label="item.nickName"
                           :value="item.userId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAssignment">确 定</el-button>
        <el-button @click="cancelAssignment">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="viewTagsOpen" append-to-body fullscreen lock-scroll>
      <policy-tag-table :policy="viewPolicy"></policy-tag-table>
    </el-dialog>
  </div>
</template>
<script>
import {getList, update} from '@/api/policy/policy'
import {getPolicyTag} from '@/api/policy/policyTag'
import {listUserByPostCode} from '@/api/system/user'
import Crontab from '@/components/Crontab'
import PolicyTagTable from './policy_tag_table'

export default {
  components: {Crontab, PolicyTagTable},
  name: "policy",
  dicts: ['core_policies'],
  data() {
    return {
      viewTagsOpen: false,
      viewPolicy: {
        policyId: null,
      },
      experts: [],
      officers: [],
      assignmentOpen: false,
      assignmentForm: {
        policyId: undefined,
        policyTitle: undefined,
        expertId: undefined,
        officerId: undefined,
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 定时政策表格数据
      policyList: [],
      corePolicies: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详细弹出层
      openView: false,
      // 是否显示Cron表达式弹出层
      openCron: false,
      // 传入的表达式
      expression: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        policyTitle: undefined,
        policyGroup: undefined,
        isHztVisible: undefined,
        isPublicVisible: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        policyId: undefined,
        coreIds: undefined
      },
      originCoreIds: [],
      // 表单校验
      rules: {
        policyName: [
          {required: true, message: "政策名称不能为空", trigger: "blur"}
        ],
        invokeTarget: [
          {required: true, message: "调用目标字符串不能为空", trigger: "blur"}
        ],
        cronExpression: [
          {required: true, message: "cron执行表达式不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    console.log('ello')

    this.getTableData()
    this.getOfficerAndExperts()
    getPolicyTag({policyId: 1}).then(response => {
      console.log(response)
    })
  },
  methods: {
    getExpertName(row) {
      let expert = this.experts.find(i => i.userId == row.expertId)
      return expert?.nickName
    },
    getOfficerName(row) {
      let officer = this.officers.find(i => i.userId == row.officerId)
      return officer?.nickName
    },
    getOfficerAndExperts() {
      listUserByPostCode('policy_expert').then(response => {
        this.experts = response
      })
      listUserByPostCode('policy_officer').then(response => {
        this.officers = response
      })
    },
    /** 查询定时政策列表 */
    getTableData() {
      this.loading = true;
      getList(this.queryParams).then(response => {
        this.policyList = response.rows.map(item => {
          item.coreIds = item.coreIds?.split(',') ?? [];
          return item;
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    // 政策组名字典翻译
    policyGroupFormat(row, column) {
      return this.selectDictLabel(this.dict.type.sys_policy_group, row.policyGroup);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        policyId: undefined,
        coreIds: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getTableData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.policyId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleRun":
          this.handleRun(row);
          break;
        case "handleEditCoreIds":
          this.handleEditCoreIds(row);
          break;
        case "handlepolicyLog":
          this.handlepolicyLog(row);
          break;
        default:
          break;
      }
    },
    // 政策状态修改
    handleStatusChange(row, field) {
      let text = row[field] === 1 ? "启用" : "停用";
      let filedName = field === 'isHztVisible' ? '对海政通' : '对公众'
      this.$modal.confirm(`确认「${row.policyTitle}」${filedName}${text}? `).then(
        () => update({
          policyId: row.policyId,
          [field]: row[field]
        }).then(() => this.$modal.msgSuccess("修改成功"))
      ).catch(() => {
        row[field]= row[field] === 1 ? 0 : 1
      })
    },
    handleEditCoreIds(row) {
      this.form = Object.assign({}, row)
      this.open = true
    },
    handleEditAssignment(row) {
      this.assignmentForm = Object.assign({}, row)
      this.assignmentOpen = true
    },
    /** 确定后回传值 */
    crontabFill(value) {
      this.form.cronExpression = value;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加政策";
    },
    /** 提交按钮 */
    submitCoreId: function () {
      update({
        coreIds: this.form.coreIds.join(','),
        policyId: this.form.policyId
      }).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getTableData();
      });
      this.open = false
      this.reset()
    },
    cancelCoreId() {
      this.open = false;
      this.reset()
    },

    submitAssignment: function () {
      update({
        expertId: this.assignmentForm.expertId,
        officerId: this.assignmentForm.officerId,
        policyId: this.assignmentForm.policyId
      }).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.assignmentOpen = false;
        this.getTableData();
      });
      this.assignmentOpen = false
    },
    cancelAssignment() {
      this.assignmentOpen = false;
      this.assignmentForm = {
        policyId: undefined,
        policyTitle: undefined,
        expertId: undefined,
        officerId: undefined
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const policyIds = row.policyId || this.ids;
      this.$modal.confirm('是否确认删除定时政策编号为"' + policyIds + '"的数据项？').then(function () {
        return delpolicy(policyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/policy/export', {
        ...this.queryParams
      }, `policy_${new Date().getTime()}.xlsx`)
    },
    handleShowTags(policy) {
      this.viewPolicy = policy
      this.viewTagsOpen = true
    }
  }
};
</script>
